<template>
  <el-row class="approve-container">
    <el-col :span="6">
      <div class="approve-table-list">
        <h-table-list
          border
          type="local"
          :data="system.records"
          highlight-current-row
          :columns="columns"
          :page-sizes="[10, 20]"
          :pagination-info="paginationInfo"
          @row-click="clickCurrentCol"
        >
          <el-button @click="addRecords">新增审批流</el-button>
          <template slot="name" slot-scope="scope">
            <el-popover trigger="hover" placement="bottom">
              <OrgTree
                :table-data="scope"
                :org-data="orgTreeData"
                :show-operate-btn="false"
              />
              <div slot="reference" class="name-wrapper">
                <el-tag size="medium">{{
                  scope.row.organizationId == -1 ? "全企业" : "指定部门"
                }}</el-tag>
              </div>
            </el-popover>
          </template>
        </h-table-list>
      </div>
    </el-col>
    <el-col :span="18">
      <div v-if="showDetail" class="business-approve-edit">
        <el-col class="approve-header-form">
          <ApproveOptions :disabled="disabled" :options="data.dataComponent" />
          <el-button class="add-node" @click="handleFilter">添加节点</el-button>

          <!-- <ListSearchParams :data-model="data" :fetch-request="handleFilter" /> -->
        </el-col>
        <el-col :span="17" class="business-approve-cards">
          <el-col v-for="(item, key) in orgData" :key="key">
            <ApproveCard
              :data="item.name"
              :index="key"
              @removeItem="removeItem"
            />
          </el-col>
        </el-col>
        <el-col :span="7">
          <SelectPerson
            v-if="system.billType == 1 || system.billType == 2"
            :options="[]"
          />
          <SelectPerson v-if="system.billType == 5" :options="options1" />
          <SelectPerson
            v-if="system.billType == 3 || system.billType == 4"
            :options="options2"
          />
          <SelectPerson v-if="system.billType == 6" :options="options3" />
          <SelectPerson v-if="system.billType == 7" :options="options4" />
          <el-col style="text-align: center">
            <el-button @click="saveTemplate">保存</el-button>
            <el-button @click="deleteTemplate">删除</el-button>
          </el-col>
        </el-col>
      </div>
    </el-col>
  </el-row>
</template>

<script>
import { mapState, mapMutations } from "vuex";
import ListSearchParams from "@/components/listSearchParams";
import TableAndButton from "@/components/TableAndButton";
import OrgTree from "@/components/orgTree";
import fetchRoleList from "@/api/system";
import ApproveCard from "./approveCard";
import SelectPerson from "./selectPerson";
import ApproveOptions from "./approveOptions";
import data from "./const";
const e = [
  {
    id: 0,
    label: "祖节点",
    children: [
      {
        id: 1,
        label: "一级 1",
        children: [
          {
            id: 4,
            label: "二级 1-1",
            children: [
              {
                id: 9,
                label: "三级 1-1-1",
              },
              {
                id: 10,
                label: "三级 1-1-2",
              },
            ],
          },
        ],
      },
      {
        id: 2,
        label: "一级 2",
        children: [
          {
            id: 5,
            label: "二级 2-1",
          },
          {
            id: 6,
            label: "二级 2-2",
          },
        ],
      },
      {
        id: 3,
        label: "一级 3",
        children: [
          {
            id: 7,
            label: "二级 3-1",
          },
          {
            id: 8,
            label: "二级 3-2",
          },
        ],
      },
    ],
  },
];

export default {
  components: {
    ListSearchParams,
    TableAndButton,
    ApproveCard,
    SelectPerson,
    ApproveOptions,
    OrgTree,
  },
  data() {
    return {
      disabled: false,
      showDetail: false,
      // 四种情况

      options1: [
        {
          multiple: true,
          type: "selectApproves",
          label: "保养确认人",
          prop: "person1",
          onchange: (e) => {
            console.log("保养确认人", e);
            this.$store.dispatch("system/updateSubmitContent", {
              preserveMan: e,
            });
          },
          option: this.$store.state.app.allUser,
        },
        {
          multiple: true,
          type: "selectApproves",
          label: "转派审核人",
          prop: "person2",
          onchange: (e) => {
            console.log("转派审核人", e);
            this.$store.dispatch("system/updateSubmitContent", {
              approveMan: e,
            });
          },
          option: this.$store.state.app.allUser,
        },
      ],
      options2: [
        {
          multiple: true,
          type: "selectApproves",
          label: "转派审核人",
          prop: "person2",
          onchange: (e) => {
            console.log("转派审核人", e);
            this.$store.dispatch("system/updateSubmitContent", {
              approveMan: e,
            });
          },
          option: this.$store.state.app.allUser,
        },
      ],
      options3: [
        {
          multiple: true,
          type: "selectApproves",
          label: "维修验收人",
          prop: "person1",
          onchange: (e) => {
            console.log("维修验收人", e);
            this.$store.dispatch("system/updateSubmitContent", { checkMan: e });
          },
          option: this.$store.state.app.allUser,
        },
        {
          multiple: true,
          type: "selectApproves",
          label: "维修分配人",
          prop: "person2",
          onchange: (e) => {
            console.log("维修分配人", e);
            this.$store.dispatch("system/updateSubmitContent", { disMan: e });
          },
          option: this.$store.state.app.allUser,
        },
        {
          multiple: true,
          type: "selectApproves",
          label: "挂起审核人",
          prop: "person3",
          onchange: (e) => {
            console.log("挂起审核人", e);
            this.$store.dispatch("system/updateSubmitContent", {
              approveMan: e,
            });
          },
          option: this.$store.state.app.allUser,
        },
      ],
      options4: [
        {
          multiple: true,
          type: "selectApproves",
          label: "维护验收人",
          prop: "person1",
          onchange: (e) => {
            console.log("维护验收人", e);
            this.$store.dispatch("system/updateSubmitContent", { checkMan: e });
          },
          option: this.$store.state.app.allUser,
        },
        {
          multiple: true,
          type: "selectApproves",
          label: "维护分配人",
          prop: "person2",
          onchange: (e) => {
            console.log("维护分配人", e);
            this.$store.dispatch("system/updateSubmitContent", { disMan: e });
          },
          option: this.$store.state.app.allUser,
        },
      ],
      data,
      orgTreeData: [],

      columns: [
        {
          prop: "billType",
          label: "审批类别",
          Width: 100,
          labelWidth: 50,
          filter: "formatApproveType",
        },
        {
          prop: "name",
          label: "审批范围",
          Width: 100,
          labelWidth: 50,
          // render:(row)=>{
          // return row.organizationId==-1?"全部门":"指定部门"
          // },
          slotName: "name",
        },

        {
          prop: "deviceName",
          label: "审批节点数",
          minWidth: 100,
          render: (row) => {
            return row.approves ? row.approves.length : 0;
          },
        },
      ],
      paginationInfo: {
        sizeChange: (e) => {
          console.log(e);
        },
        currentChange: (e) => {
          this.$store.dispatch("system/setListSearchParams", {
            current: e,
          });
          this.getList({ current: e });
        },
        current: 1,
        total: 10,
      },
      tableData: [],
      tableKey: 3,
      list: [],
      orgData: this.$store.state.system.approveItem.approves, // [{name:1,i:1}]
    };
  },
  computed: {
    ...mapState(["system", "app"]),
  },
  watch: {
    "this.$store.state.app.allUser": {
      handler(newData, oldData) {
        this.$set(this.options1, "option", this.$store.state.app.allUser);
        this.$set(this.options2, "option", this.$store.state.app.allUser);
        this.$set(this.options3, "option", this.$store.state.app.allUser);
        this.$set(this.options4, "option", this.$store.state.app.allUser);
      },
      immediate: true,
    },
    // ...mapState(["system","app"]),
  },
  created() {
    // (this.data.dataComponent)[1].optionData=this.optionData(listData)
    this.$store
      .dispatch(this.$store_url_button, {
        add: this.add,
        export: this.export,
        delete: this.delete,
        edit: this.edit,
        detail: this.detail,
        using: this.using,
        useless: this.useless,
        downloadTemplete: this.downloadTemplete,
        downloadIdentify: this.downloadIdentify,
      })

      .then(async () => {
        await this.getList(); // 表格数据
        await this.$store.dispatch("app/getCodeList", ["department"]); // code转码
        await this.$store.dispatch("app/updateAllUser"); // 拉取人员信息
        this.$set(
          this.data.dataComponent[1],
          "optionData",
          this.optionData(this.$store.state.app.allCode.department)
        );
        this.$set(
          this,
          "orgTreeData",
          this.optionData(this.$store.state.app.allCode.department)
        );
      });
  },
  methods: {
    // //对组织树高亮
    // formOrgData(row){
    //     //this.$set(this,"orgTreeData",this.optionData(this.$store.state.app.allCode.department,row.organIds))

    //     return this.orgTreeData
    // },
    // 选中当前数据项
    clickCurrentCol(row, column, e) {
      this.disabled = true;
      this.showDetail = true;
      this.$store.dispatch("system/updateApproveItem", row);
      console.log(
        this.$store.state.system.approveItem.approves,
        "+++approves+++="
      );

      if (this.$store.state.system.approveItem.approves) {
        const arrays = this.$store.state.system.approveItem.approves.map(
          (e) => {
            e.name = e.resMan.map((item) => {
              return item.id + "," + item.name;
            });
            return e;
          }
        );
        console.log(arrays, "++arrays+++");
        console.log(this.orgData, "++++orgData+++");
        this.$set(this, "orgData", arrays); // 填充审批人信息

        this.$set(
          this.data.dataComponent[0],
          "value",
          this.$store.state.system.approveItem.billType
        ); // 填充审批类别
        this.$set(
          this.data.dataComponent[1],
          "value",
          this.$store.state.system.approveItem.organIds
        ); // 填充审批范围
      } else {
        // 点击空白项则无填充
      }

      // this.$set(this.options[0],"option",this.$store.state.system.approveItem.approves)  //填充保养人/转派人等信息
      // this.$set(this.options[1],"option",this.$store.state.system.approveItem.approves)  //填充保养人/转派人等信息
    },
    // 保存模板
    saveTemplate() {
      console.log(this.$store.state.system, "+++报存+++");
      this.$store.dispatch("system/saveTemplate");
      this.getList({ current: 1 });
    },
    //删除模板
    deleteTemplate() {
      console.log(this.$store.state.system.approveItem, "+++approveItem+++");
      this.$confirm(
        `确认删除审批流？删除后该范围内业务将不再需要审批`,
        "删除审批流",
        {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning",
        }
      )
        .then(async () => {
          this.$store.dispatch(
            "system/delApproveTemplate",
            this.$store.state.system.approveItem.id
          );
          await this.getList({ current: 1 });
          this.$set(this, "orgData", []); // 填充审批人信息

          this.$set(this.data.dataComponent[0], "value", null); // 填充审批类别

          this.$set(this.data.dataComponent[1], "value", null); // 填充审批范围
        })
        .catch(() => {
          this.$message({
            type: "info",
            message: "已取消删除",
          });
        });
    },
    // 选择节点或者人员时存放到vuex
    onChange(e) {
      console.log("审批人", e);
    },
    // 新增一条审批模板
    addRecords(e) {
      this.disabled = false;
      this.showDetail = true;
      // this.$store.dispatch("system/addOneRole", {});
      this.$set(this, "orgData", []); // 填充审批人信息
      // this.orgData.push({
      //   name: 1,
      //   i: 1
      // });

      this.$set(this.data.dataComponent[0], "value", null); // 填充审批类别
      this.$set(this.data.dataComponent[1], "value", []); // 填充审批范围
    },
    // 转树形结构
    optionData(e, b) {
      const cloneData = JSON.parse(JSON.stringify(e)); // 对源数据深度克隆
      // 这里加一个逻辑，在选择范围字段编辑和新增的下拉中直接显示，在表格中更需要过滤对比存在的数据高亮,e为元数据,b为对比数据
      // if(b){
      //
      //  //b存在则对比较数据循环对比
      //   a.forEach(e=>{
      //     if(b.indexOf(e.id)){
      //        e.highlight=true
      //     }
      //   })

      // }
      return cloneData.filter((father) => {
        // 循环所有项，并添加children属性
        const branchArr = cloneData.filter(
          (child) => father.id == child.parentId
        ); // 返回每一项的子级数组
        father.name = father.organName;
        father.label = father.organName;
        branchArr.name = branchArr.organName;
        branchArr.label = branchArr.organName;
        branchArr.length > 0 ? (father.children = branchArr) : ""; // 给父级添加一个children属性，并赋值
        return father.parentId == 0; // 返回第一层
      });
    },
    handleFilter(args) {
      console.log(this.orgData.length, "------");
      if (this.orgData.length < 5) {
        this.orgData.push({
          name: this.orgData.length,
          i: this.orgData.length + 1,
        });
      } else {
        this.$message("最多只能添加五级审批节点");
      }
    },
    async getList(args) {
      // this.listLoading = true
      console.log(args);
      await this.$store.dispatch("system/requestRoleList", args);
      // 设置total;
      this.paginationInfo.total = this.$store.state.system.total;
      this.paginationInfo.current = 1;
    },
    removeItem(i) {
      console.log(i, "++iii+++");
      this.orgData.splice(i, 1);
    },
  },
};
</script>

<style lang="scss">
.approve-container {
  min-width: 1560px;
}
.org-tree-show {
  background: #f6f8fa;
}
.approve-table-list {
  float: left;
  height: 875px;
  background: white;
  padding: 10px;
  // min-width: 450px;
}
.business-approve-edit {
  float: right;
  min-width: 1100px;
  padding: 10px;
  height: 875px;
  background: white;
  position: relative;
  .approve-header-form {
    border-bottom: 2px solid #e5e5e5;
  }
}
.business-approve-cards {
  height: 850px;
  position: relative;
  background: #f5f6fa;
  margin: 10px 0;
}
.equipment-detail-button {
  border-bottom: 2px solid #e5e5e5;
  padding: 10px 0;
}
.add-node {
  display: inline-block;
}
</style>
